<template>
	<uni-nav-bar fixed="true" statusBar="true" border="false" left-icon="left" title="支付" @clickLeft="back"></uni-nav-bar>
	<view class="payment-container">
		<view class="payment-header">
			<image class="w45 mb20" :src="paymentIcon" mode="widthFix"></image>
			<view class="mb30">等待支付</view>
			<view>
				<view class="tc mb30">{{ countdownDisplay }}</view>
				<view class="mb30">超时未支付订单将自动取消</view>
			</view>
		</view>
		<view>
			<view class="mb30">
				<text>订单编号：</text>
				<text>{{ Data.orderNo }}</text>
			</view>
			<view class="mb30">
				<text>支付金额：</text>
				<text>{{ Data.itineraryFee }}</text>
			</view>
		</view>
		<view class="fixed-bottom-wrap">
			<view class="schdule-card uni-flex">
				<view class="flex-item wd100 sign bg-green tc color_white" @tap="goToPay()">
					<text>去支付</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/common/api/webapi.js'; /*api*/
	export default {
		data() {
			return {
				paymentIcon: '/static/paying.png',
				Data:{
					orderNo:'',
					itineraryFee:'',
				},
				countdown: 300, // 5分钟 = 300秒
				timer: null
			}
		},
		onLoad(option) {
			if(option.param){
				let params = JSON.parse(decodeURIComponent(option.param));
				this.Data = params;
			}
			// 启动倒计时
			this.startCountdown();
		},
		onUnload() {
			// 页面卸载时清除定时器
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		computed: {
			countdownDisplay() {
				const minutes = Math.floor(this.countdown / 60);
				const seconds = this.countdown % 60;
				return `${minutes.toString().padStart(2, '0')}: ${seconds.toString().padStart(2, '0')}`;
			}
		},
		methods: {
			back(){
				uni.navigateBack();
			},
			startCountdown() {
				this.timer = setInterval(() => {
					if (this.countdown > 0) {
						this.countdown--;
					} else {
						// 倒计时结束，取消订单
						this.cancelOrder();
					}
				}, 1000);
			},
			
			cancelOrder() {
				// 清除定时器
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
				
				// 这里可以调用取消订单的API
				// 取消后返回上一页或跳转到订单列表
				uni.showToast({
					title: '订单已取消',
					icon: 'none'
				});
				
				// 延迟返回，让用户看到提示
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			},
			
			goToPay() {
				let that = this;
				let params = {
					orderNo: that.Data.orderNo,
					orderPayChannel:'WECHAT',
				};
				api.payApp(params).then(res => {
					if (res.code === 0) {
						uni.requestPayment({
							provider: "wxpay",
							nonceStr: res.data.nonceStr, // 随机字符串
							package: res.data.package, // 固定值
							signType: res.data.signType, // 固定值
							timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
							paySign: res.data.paySign, // 签名，这里用的 MD5/RSA 签名
							success(res) {
								uni.hideLoading();
								console.log("支付成功返回数据",res);
								console.log("that.Data",that.Data);
								let notifyParams = {
									params: {
										orderNo: that.Data.orderNo,
										orderPayChannel:'WECHAT'
									}
								}
								api.payNotify(notifyParams).then(notifyRes => {
									console.log("支付通知返回数据",notifyRes);
									if (notifyRes.code == 0) {
										let tradeInfo = {
											orderNo: notifyRes.data.orderNo,
											thirdFlowNo: notifyRes.data.thirdFlowNo,
											payResult: notifyRes.data.payResult,
										};
										console.log("跳转到成功页面的参数",tradeInfo);
										uni.navigateTo({
											url:"/pages/sucess/sucess?param="+encodeURIComponent(JSON.stringify(tradeInfo))
										})
									} else {
										// 即使通知失败，也尝试跳转到成功页面
										let tradeInfo = {
											orderNo: that.Data.orderNo,
											thirdFlowNo: '',
											payResult: '',
										};
										console.log("通知失败但仍尝试跳转",tradeInfo);
										uni.navigateTo({
											url:"/pages/sucess/sucess?param="+encodeURIComponent(JSON.stringify(tradeInfo))
										})
									}
									uni.hideLoading();
								}).catch(err=>{
									console.log("支付通知请求失败",err);
									// 请求失败也尝试跳转到成功页面
									let tradeInfo = {
										orderNo: that.Data.orderNo,
										itineraryFee: that.Data.itineraryFee
									};
									uni.navigateTo({
										url:"/pages/sucess/sucess?param="+encodeURIComponent(JSON.stringify(tradeInfo))
									})
								})
							},
							fail(e) {
								console.log("支付失败",e);
								uni.hideLoading();
								uni.showToast({
									icon: 'none',
									title: res.msg || '支付失败'
								});
							}
						})
					} else {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: res.msg || '请求支付失败'
						});
						uni.switchTab({
							url: '/pages/index/index',
							success() {
								var page = getCurrentPages().pop();
								if (page == undefined || page == null) return;
								page.onLoad();
							}
						})
					}
				}).catch(err => {
					console.log("发起支付请求失败", err);
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '发起支付请求失败'
					});
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.payment-container {
		padding: 60rpx 40rpx;
		background-color: #ffffff;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.payment-header {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 100rpx;
	}
</style>